package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"github.com/spf13/cast"
	"law_case_api/dto"
	"law_case_api/models"
	"law_case_api/services"
	"law_case_api/utils"
	"net/http"
	"strconv"
	"time"
)

// @Summary 根据条件获取客户列表
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param GetCustomerList body dto.CustomerListReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/list [post]
func GetCustomerList(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	customerListReq := dto.CustomerListReq{}
	if err := c.Bind(&customerListReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	isLaw := false
	LoginType := c.Request().Header["Logintype"]
	if len(LoginType) > 0 {
		if LoginType[0] == "1" {
			isLaw = true
		}
	}
	customer := services.CustomerService{}
	respData, respPageCount, err := customer.GetCustomerList(userid, isLaw, customerListReq)
	if err != nil {
		resp.Code = 400
		return c.JSON(http.StatusOK, resp)
	}

	resp.PageCount = respPageCount
	var data []*dto.CustomerListResp
	utils.MapTo(respData, &data)
	var CustomerIds []int64
	for _, v := range data {
		CustomerIds = append(CustomerIds, v.Id)
	}
	_case := services.CaseService{}
	contract := services.ContractService{}
	CaseObjectCountMap := _case.GetCaseCountByCondition(CustomerIds)
	ContractObjectCountMap := contract.GetContractCountByCondition(CustomerIds)
	for _, v := range data {
		if _, ok := CaseObjectCountMap[v.Id]; ok {
			v.CaseCount = CaseObjectCountMap[v.Id].ObjectCount
		}
		if _, ok := ContractObjectCountMap[v.Id]; ok {
			v.ContractCount = ContractObjectCountMap[v.Id].ObjectCount
		}
	}
	resp.Data = data
	return c.JSON(http.StatusOK, resp)
}

// @Summary 根据id获取客户详情
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param customerId query string true "客户id"
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/get [get]
func GetCustomerInfo(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	customerId, _ := strconv.Atoi(c.QueryParam("customerId"))
	if customerId == 0 {
		resp.Code = 400
		resp.Message = "客户编号不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	customer := services.CustomerService{}

	wzjCustomerInfo, wzjCustomerInvoice, wzjCustomerLegal, err := customer.GetCustomerInfoById(customerId)
	if err != nil {
		resp.Code = 400
		resp.Message = "根据客户id查询客户信息失败"
		return c.JSON(http.StatusOK, resp)
	}
	//格式化
	customerResp := dto.CreateCustomerReq{}
	utils.MapTo(wzjCustomerInfo, &customerResp)
	customerResp.InvoiceAddress = wzjCustomerInvoice.InvoiceAddress
	customerResp.InvoiceBankAccountNumber = wzjCustomerInvoice.InvoiceBankAccountNumber
	customerResp.InvoiceBankDeposit = wzjCustomerInvoice.InvoiceBankDeposit

	customerResp.LegalIdCard = wzjCustomerLegal.LegalIdCard
	customerResp.LegalName = wzjCustomerLegal.LegalName
	customerResp.LegalPost = wzjCustomerLegal.LegalPost

	resp.Data = customerResp
	return c.JSON(http.StatusOK, resp)
}

// @Summary 创建客户信息
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param CreateCustomer body dto.CreateCustomerReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/create [post]
func CreateCustomer(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)

	createCustomerReq := dto.CreateCustomerReq{}
	if err := c.Bind(&createCustomerReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	//基础参数验证判断
	if len(createCustomerReq.UnifySocialCreditCode) == 0 {
		resp.Code = 400
		resp.Message = "统一社会信用代码不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	//判断是否已存在
	customer := services.CustomerService{}
	if customerInfo, err := customer.GetCustomerInfoByUnifySocialCreditCode(createCustomerReq.UnifySocialCreditCode); err != nil {
		resp.Code = 400
		resp.Message = "判断统一社会信用代码唯一性失败，请重试"
		return c.JSON(http.StatusOK, resp)
	} else {
		if customerInfo.Id > 0 {
			if createCustomerReq.Id > 0 {
				if customerInfo.Id != createCustomerReq.Id {
					resp.Code = 400
					resp.Message = "该统一社会信用代码已存在，请重新填写"
					return c.JSON(http.StatusOK, resp)
				}
			} else {
				resp.Code = 400
				resp.Message = "该统一社会信用代码已存在，请重新填写"
				return c.JSON(http.StatusOK, resp)
			}
		}
	}

	//解决对象映射
	wzjCustomerInfo := models.WzjCustomerInfo{}
	wzjCustomerInvoice := models.WzjCustomerInvoice{}
	wzjCustomerLegal := models.WzjCustomerLegal{}
	utils.MapTo(createCustomerReq, &wzjCustomerInfo)
	wzjCustomerInfo.CustomerOwner = cast.ToInt32(claims.UserId) //把客户归属到当前操作人身上
	utils.MapTo(createCustomerReq, &wzjCustomerInvoice)
	utils.MapTo(createCustomerReq, &wzjCustomerLegal)

	if createCustomerReq.Id > 0 {
		//编辑
		wzjCustomerInvoice.CustomerId = createCustomerReq.Id
		wzjCustomerLegal.CustomerId = createCustomerReq.Id
		boolRes, err := customer.UpdateCustomer(wzjCustomerInfo, wzjCustomerInvoice, wzjCustomerLegal)
		if err == nil && boolRes {
			resp.Message = "更新客户成功"
			return c.JSON(http.StatusOK, resp)
		}
		log.Error("更新客户失败：", err) //增加日志信息
		resp.Code = 400
		resp.Message = "更新客户失败"
		return c.JSON(http.StatusOK, resp)
	} else {
		//新建
		wzjCustomerInfo.CreateDate = time.Now().Unix()
		wzjCustomerInfo.CustomerPwd = "123456" //默认密码
		wzjCustomerInfo.CustomerCode = utils.GenerateSpecialCode("YKHC")
		boolRes, err := customer.CreateCustomer(wzjCustomerInfo, wzjCustomerInvoice, wzjCustomerLegal)
		if err == nil && boolRes {
			resp.Message = "创建客户成功"
			return c.JSON(http.StatusOK, resp)
		}
		log.Error("创建客户失败：", err) //增加日志信息
		resp.Code = 400
		resp.Message = "创建客户失败"
		return c.JSON(http.StatusOK, resp)
	}

}

// @Summary 获取当前登录人可查看的客户列表-用于select
// @Tags 客户管理
// @Accept plain
// @Produce plain
// @Param customer_type query string true "客户类型"
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/customer/select [get]
func GetCustomerSelect(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	isLaw := false
	LoginType := c.Request().Header["Logintype"]
	if len(LoginType) > 0 {
		if LoginType[0] == "1" {
			isLaw = true
		}
	}
	customerType, _ := strconv.Atoi(c.QueryParam("customer_type"))
	customer := services.CustomerService{}
	selectValue, err := customer.GetCustomerInfoForSelectByOwner(userid, customerType, isLaw)
	if err != nil {
		resp.Code = 400
		resp.Message = "根据客户id查询客户信息失败"
		return c.JSON(http.StatusOK, resp)
	}
	resp.Data = selectValue
	return c.JSON(http.StatusOK, resp)
}
